package myky.com.doctorapp.utils;

import android.content.ContentUris;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.blankj.utilcode.util.FileUtils;
import com.github.nukc.stateview.Constant;

import myky.com.doctorapp.api.Address;
import myky.com.doctorapp.base.CMApplication;


/**
 *
 * Description: Uri转换工具类，优化内存占用
 * @author xiangyao
 * Created by 2019/3/6 11:16 AM
 */
public class UriUtils {
    private  Uri uri;
    private  String path = Constant.STRINGDEFAULT;
    private  int resId = Constant.INTDEFAULT;
    private  static   UriUtils uriUtils;

    private UriUtils(){

    }

    public  static UriUtils getUriInstance(){
        if(uriUtils==null){
            synchronized (UriUtils.class){
                if(uriUtils==null){
                    uriUtils=new UriUtils();
                }
            }
        }
        return  uriUtils;

    }

    public Uri getUri(int mode, String url) {
        path = url;

        return !TextUtils.isEmpty(path) ? UriTool(mode) : null;

    }

    public Uri getUri(int mResId) {
        resId = mResId;

        return !TextUtils.isEmpty(path) ? UriTool(Constant.LOCALRESOURCE) : null;
    }
    public   Uri getUri(String url) {
        path = url;

        return !TextUtils.isEmpty(path) ? FileUtils.isFileExists(url)?UriTool(Constant.PHONEIMAGEPATH):UriTool(Constant.ONLINEPIC): null;
    }
    public  Uri getUri(int mode, int localResource) {
        resId = localResource;
        return UriTool(mode);
    }

    private   Uri UriTool(int mode) {
        if (mode == Constant.ONLINEPIC && !path.equals(Constant.STRINGDEFAULT)) {
            if(path.startsWith("http")){
                uri = Uri.parse(path);
            }else {
                uri = Uri.parse(Address.IMAGE+path);
            }

        } else if (mode == Constant.LOCALRESOURCE && resId != Constant.INTDEFAULT) {
            uri = Uri.parse("res://" + CMApplication.getAppContext().getPackageName() + "/" + resId);
        }else if(mode==Constant.PHONEIMAGEPATH&& !path.equals(Constant.STRINGDEFAULT)){

            Uri mediaUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            Cursor cursor = CMApplication.getAppContext().getContentResolver().query(mediaUri,
                    null,
                    MediaStore.Images.Media.DISPLAY_NAME + "= ?",
                    new String[] {path.substring(path.lastIndexOf("/") + 1)},
                    null);

            Uri uri = null;
            if(cursor.moveToFirst()) {
                uri = ContentUris.withAppendedId(mediaUri,
                        cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media._ID)));
            }
            cursor.close();
            return uri;

        }

        return uri;
    }

}
